//
//  CustomerServiceViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2018/11/30.
//  Copyright © 2018 lifayu. All rights reserved.
//

#import "CustomerServiceViewController.h"
#import "CSPostMessageRequest.h"
#import "CSGetMSGListRequest.h"
#import "CustomTextMessageTableViewCell.h"
#import "FlyMainTabBarViewController.h"

@interface CustomerServiceViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewBottom;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (strong, nonatomic) CSListModel *messageListModel;
@property (strong, nonatomic) NSTimer *loopTimer;
@property (assign, nonatomic) NSInteger currentPage;

@end

@implementation CustomerServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[HUDHelper sharedInstance] syncLoading];
    _currentPage = 1;
    [self getMessageList];
}

- (NSTimer *)loopTimer{
    if(!_loopTimer){
        _loopTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(loopGetNewMessage) userInfo:nil repeats:YES];
    }
    return _loopTimer;
}

- (void)configOwnViews{
    self.title = @"在线客服";
    [self.tableView registerClass:[CustomTextMessageTableViewCell class] forCellReuseIdentifier:@"CustomTextMessageTableViewCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage ++;
        [self getMessageList];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    FlyMainTabBarViewController *tabbarvc = (FlyMainTabBarViewController *)self.tabBarController;
    tabbarvc.csButton.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    FlyMainTabBarViewController *tabbarvc = (FlyMainTabBarViewController *)self.tabBarController;
    tabbarvc.csButton.hidden = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(_loopTimer){
        [_loopTimer invalidate];
        _loopTimer = nil;
    }
}

- (void)loopGetNewMessage{
    CSGetMSGListRequest *req = [CSGetMSGListRequest new];
    req.csMsgId = self.messageListModel.csMsgId;
    req.hideLoadingView = YES;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] syncStopLoading];
        CSListModel *model = response.data;
        if(model){
            weakSelf.messageListModel = model;
            if(weakSelf.messageListModel.list.count > 0){
                [weakSelf.dataSource insertObjects:weakSelf.messageListModel.list atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, weakSelf.messageListModel.list.count)]];
            }
            [weakSelf.tableView reloadData];
            if(weakSelf.messageListModel.list.count > 0){
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
        }
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [weakSelf.tableView.mj_header endRefreshing];
        DebugLog(@"获取消息列表失败，%@", response.message);
    }];
}

- (void)getMessageList{
    CSGetMSGListRequest *req = [CSGetMSGListRequest new];
    req.page = @(_currentPage).stringValue;
    req.pageLimit = @"20";
    req.hideLoadingView = YES;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] syncStopLoading];
        CSListModel *model = response.data;
        weakSelf.messageListModel = model;
        if(weakSelf.currentPage == 1){
            weakSelf.dataSource = [NSMutableArray arrayWithArray:model.list];
        }else{
            [weakSelf.dataSource addObjectsFromArray:model.list];
        }
        if(weakSelf.messageListModel.list.count < 20){
            weakSelf.currentPage = weakSelf.messageListModel.totalPages.integerValue;
        }
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView reloadData];
        if(weakSelf.dataSource.count > 0){
            if(weakSelf.currentPage == 1){
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
        }
        [weakSelf.loopTimer fire];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [weakSelf.tableView.mj_header endRefreshing];
        DebugLog(@"获取消息列表失败，%@", response.message);
        [weakSelf.loopTimer fire];
    }];
}

#pragma mark - Keyboard behavior
- (void)keyboardWillHide:(__unused NSNotification *)inputViewNotification {
    NSInteger duration = [inputViewNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    FlyWeakSelf
    [UIView animateWithDuration:duration animations:^{
        weakSelf.inputViewBottom.constant = 0;
        [weakSelf.view layoutIfNeeded];
        if(weakSelf.dataSource.count > 0){
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }];
}

- (void)keyboardWillShow:(__unused NSNotification *)inputViewNotification {
    CGRect inputViewFrame = [[[inputViewNotification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSInteger duration = [inputViewNotification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    FlyWeakSelf
    [UIView animateWithDuration:duration animations:^{
        weakSelf.inputViewBottom.constant = -inputViewFrame.size.height;
        [weakSelf.view layoutIfNeeded];
        if(weakSelf.dataSource.count > 0){
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    }];
}

- (IBAction)sendAction:(UIButton *)sender {
    [self sendMessageText];
}

- (void)sendMessageText{
    [self.view endEditing:YES];
    if(self.textField.text && self.textField.text.length > 0){
        CSPostMessageRequest *req = [CSPostMessageRequest new];
        req.content = self.textField.text;
        FlyWeakSelf
        [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
           weakSelf.currentPage = 1;
            [weakSelf getMessageList];
        } failHandler:^(BaseResponse *response) {
            [[HUDHelper sharedInstance] tipMessage:response.message];
        }];
    }
    self.textField.text = nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self sendMessageText];
    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CustomTextMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomTextMessageTableViewCell" forIndexPath:indexPath];
    cell.messageModel = self.dataSource[(self.dataSource.count - 1) - indexPath.row];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [CustomTextMessageTableViewCell cellHeightForMessageModel:self.dataSource[(self.dataSource.count - 1) - indexPath.row]];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *view = [UITableViewHeaderFooterView new];
    view.contentView.backgroundColor = kClearColor;
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *view = [UITableViewHeaderFooterView new];
    view.contentView.backgroundColor = kClearColor;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 16;
}

@end
